import React, { useState, useEffect } from 'react';
import {
  Button,
  InputNumber,
  Select,
  Space,
  Typography,
  Form,
  Alert,
} from 'antd';
import InterviewQuestion from './InterviewQuestion';

const { Option } = Select;
const { Title } = Typography;

const InterviewSimulator = () => {
  const [mode, setMode] = useState('select');
  const [questions, setQuestions] = useState([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [timePerQuestion, setTimePerQuestion] = useState(10);
  const [totalQuestions, setTotalQuestions] = useState(10);
  const [timeLeft, setTimeLeft] = useState(timePerQuestion);
  const [currentQuestionTimeLeft, setCurrentQuestionTimeLeft] = useState(
    timePerQuestion * 60
  );

  useEffect(() => {
    if (mode === 'question') {
      setCurrentQuestionTimeLeft(timePerQuestion * 60);
      const timer = setInterval(() => {
        setCurrentQuestionTimeLeft(prevTime => prevTime - 1);
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [mode, currentQuestionIndex, timePerQuestion]);

  const startInterview = () => {
    setMode('question');
  };

  const fetchQuestions = async (bankType, count) => {
    const response = await fetch(
      `http://localhost:29157/api/tools/testDb/${bankType}/${count}`
    );
    const data = await response.json();
    setQuestions(data.data.testDbList);
    startInterview(); // 移动到这里
  };

  const handleConfigSubmit = () => {
    fetchQuestions('java', totalQuestions);
    // 删除 startInterview() 调用
  };

  const handleFinishQuestion = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
    } else {
      setMode('result');
    }
  };

  const handleRestart = () => {
    setMode('select');
    setCurrentQuestionIndex(0);
  };

  const renderContent = () => {
    const remainingTime =
      timeLeft * 60 - currentQuestionIndex * timePerQuestion * 60;
    if (mode === 'select') {
      return (
        <div>
          <Typography.Title level={3}>面试模拟器</Typography.Title>
          <Typography.Paragraph>
            1.
            题库支持选择题库和自定义题库（自定义题库将在下个小版本开发敬请期待）
          </Typography.Paragraph>
          <Typography.Paragraph>
            2. 选择题库时可以选择单词模拟考试的题目数量和限定时间。
          </Typography.Paragraph>
          <Typography.Paragraph>
            3. 题目分数由当题结束后自己看答案裁定。不提供打分功能。
          </Typography.Paragraph>
          <Typography.Paragraph>4. 结束后可以开始重新答题</Typography.Paragraph>
          <Button
            onClick={() => setMode('config')}
            style={{ marginTop: '1rem' }}>
            选择题库模式
          </Button>
          {/* 更多模式的按钮 */}
        </div>
      );
    }
    if (mode === 'config') {
      return (
        <div>
          <Title level={3}>配置面试</Title>
          <Form layout='vertical'>
            <Form.Item label='选择题库'>
              <Select
                defaultValue='java'
                style={{ width: 200 }}>
                <Option value='java'>Java 题库</Option>
              </Select>
            </Form.Item>
            <Form.Item label='题目数量'>
              <InputNumber
                min={5}
                max={50}
                defaultValue={10}
                onChange={setTotalQuestions}
              />
            </Form.Item>
            <Form.Item label='每题时间限制（分钟）'>
              <InputNumber
                min={1}
                max={30}
                defaultValue={10}
                onChange={setTimePerQuestion}
              />
            </Form.Item>
            <Form.Item>
              <Button onClick={handleConfigSubmit}>开始答题</Button>
            </Form.Item>
          </Form>
        </div>
      );
    }

    if (mode === 'question') {
      return (
        <div>
          <Alert
            message={`剩余时间: ${Math.max(
              Math.floor(currentQuestionTimeLeft / 60),
              0
            )} 分 ${Math.max(currentQuestionTimeLeft % 60, 0)} 秒, 当前题目: ${
              currentQuestionIndex + 1
            }`}
            type='info'
          />
          {questions.length > 0 && currentQuestionIndex < questions.length ? (
            <InterviewQuestion
              question={questions[currentQuestionIndex]}
              onFinish={handleFinishQuestion}
              timePerQuestion={timePerQuestion}
            />
          ) : (
            <p>加载问题中，请稍候...</p>
          )}
        </div>
      );
    }

    if (mode === 'result') {
      return (
        <div>
          <Title level={3}>考试结束</Title>
          <Button onClick={handleRestart}>重新开始</Button>
        </div>
      );
    }

    return <div>未知模式</div>;
  };

  return <div>{renderContent()}</div>;
};

export default InterviewSimulator;
